/// 集合详情页面
/// 
/// 显示视频集合的详细信息，管理视频和白名单
/// 
/// @author Matrix
/// @version 1.0.0
/// @since 2025-11-26

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_compress/video_compress.dart';
import '../../models/collection_model.dart';
import '../../services/collection_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import '../../utils/compress_utils.dart';

/// 集合详情页面
class CollectionDetailPage extends StatefulWidget {
  /// 集合模型
  final CollectionModel collection;
  
  /// 是否是共享视图（只读模式）
  final bool isSharedView;

  const CollectionDetailPage({
    super.key,
    required this.collection,
    this.isSharedView = false,
  });

  @override
  State<CollectionDetailPage> createState() => _CollectionDetailPageState();
}

class _CollectionDetailPageState extends State<CollectionDetailPage>
    with SingleTickerProviderStateMixin {
  /// 集合服务
  final CollectionService _collectionService = CollectionService();
  
  /// Tab控制器
  late TabController _tabController;
  
  /// 集合详情（最新数据）
  late CollectionModel _collection;
  
  /// 视频列表
  List<CollectionVideoModel> _videos = [];
  
  /// 白名单列表
  List<WhitelistUserModel> _whitelistUsers = [];
  
  /// 是否正在加载视频
  bool _isLoadingVideos = false;
  
  /// 是否正在加载白名单
  bool _isLoadingWhitelist = false;
  
  /// 是否有修改
  bool _hasChanges = false;

  @override
  void initState() {
    super.initState();
    _collection = widget.collection;
    _tabController = TabController(length: 2, vsync: this);
    // 监听Tab切换，更新FloatingActionButton
    _tabController.addListener(_onTabChanged);
    _loadVideos();
    if (_collection.isWhitelist) {
      _loadWhitelist();
    }
  }

  /// Tab切换时触发重建
  void _onTabChanged() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose();
    super.dispose();
  }

  /// 加载视频列表
  Future<void> _loadVideos() async {
    if (_isLoadingVideos) return;
    setState(() => _isLoadingVideos = true);

    try {
      final videos = await _collectionService.getCollectionVideos(_collection.id);
      setState(() {
        _videos = videos;
        _isLoadingVideos = false;
      });
      Logger.d('COLLECTION_DETAIL', '加载视频成功，共 ${videos.length} 个');
    } catch (e) {
      Logger.e('COLLECTION_DETAIL', '加载视频失败: $e');
      setState(() => _isLoadingVideos = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载视频失败: $e')),
        );
      }
    }
  }

  /// 加载白名单列表
  Future<void> _loadWhitelist() async {
    if (_isLoadingWhitelist) return;
    setState(() => _isLoadingWhitelist = true);

    try {
      final result = await _collectionService.getWhitelistUsers(
        collectionId: _collection.id,
      );
      setState(() {
        _whitelistUsers = result.records;
        _isLoadingWhitelist = false;
      });
      Logger.d('COLLECTION_DETAIL', '加载白名单成功，共 ${result.records.length} 个');
    } catch (e) {
      Logger.e('COLLECTION_DETAIL', '加载白名单失败: $e');
      setState(() => _isLoadingWhitelist = false);
    }
  }

  /// 刷新集合详情
  Future<void> _refreshCollection() async {
    try {
      final collection = await _collectionService.getCollectionDetail(_collection.id);
      setState(() => _collection = collection);
    } catch (e) {
      Logger.e('COLLECTION_DETAIL', '刷新集合详情失败: $e');
    }
  }

  /// 播放视频
  void _playVideo(CollectionVideoModel video) {
    // 记录播放
    _collectionService.recordVideoPlay(video.id);
    
    // 直接使用视频播放对话框
    _showVideoPlayer(video);
  }
  
  /// 显示视频播放器
  void _showVideoPlayer(CollectionVideoModel video) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => Dialog(
        backgroundColor: Colors.black,
        insetPadding: EdgeInsets.zero,
        child: Stack(
          children: [
            Center(
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: Container(
                  color: Colors.black,
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.play_circle_outline, 
                             size: 64, color: Colors.white.withOpacity(0.8)),
                        const SizedBox(height: 16),
                        Text(
                          video.title,
                          style: const TextStyle(color: Colors.white, fontSize: 16),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '视频URL: ${video.videoUrl}',
                          style: TextStyle(color: Colors.white.withOpacity(0.6), fontSize: 12),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 16),
                        ElevatedButton.icon(
                          onPressed: () {
                            // TODO: 实现实际的视频播放
                            Navigator.pop(context);
                          },
                          icon: const Icon(Icons.play_arrow),
                          label: const Text('播放视频'),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              top: 40,
              right: 20,
              child: IconButton(
                icon: const Icon(Icons.close, color: Colors.white, size: 28),
                onPressed: () => Navigator.pop(context),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 删除视频
  void _deleteVideo(CollectionVideoModel video) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除视频'),
        content: Text('确定要从集合中删除视频"${video.title}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _collectionService.deleteVideo(video.id);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('删除成功')),
                );
                _hasChanges = true;
                _loadVideos();
                _refreshCollection();
              } catch (e) {
                Logger.e('COLLECTION_DETAIL', '删除视频失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('删除失败: $e')),
                );
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 添加白名单用户
  void _addWhitelistUser() {
    final controller = TextEditingController();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加白名单用户'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            labelText: '用户名',
            hintText: '请输入用户名，多个用户用逗号分隔',
            border: OutlineInputBorder(),
          ),
          maxLines: 3,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final text = controller.text.trim();
              if (text.isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('请输入用户名')),
                );
                return;
              }
              
              Navigator.pop(context);
              
              // 解析用户名列表
              final usernames = text.split(',')
                  .map((e) => e.trim())
                  .where((e) => e.isNotEmpty)
                  .toList();
              
              try {
                final count = await _collectionService.addWhitelistUsers(
                  collectionId: _collection.id,
                  usernames: usernames,
                );
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('成功添加 $count 个用户')),
                );
                _hasChanges = true;
                _loadWhitelist();
              } catch (e) {
                Logger.e('COLLECTION_DETAIL', '添加白名单失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('添加失败: $e')),
                );
              }
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  /// 移除白名单用户
  void _removeWhitelistUser(WhitelistUserModel user) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('移除用户'),
        content: Text('确定要将用户"${user.username ?? '未知'}"从白名单中移除吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _collectionService.removeWhitelistUser(
                  collectionId: _collection.id,
                  targetUserId: user.userId,
                );
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('移除成功')),
                );
                _hasChanges = true;
                _loadWhitelist();
              } catch (e) {
                Logger.e('COLLECTION_DETAIL', '移除白名单失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('移除失败: $e')),
                );
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('移除'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Navigator.pop(context, _hasChanges);
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(_collection.title),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () => Navigator.pop(context, _hasChanges),
          ),
          bottom: TabBar(
            controller: _tabController,
            tabs: [
              Tab(text: '视频 (${_collection.videoCount})'),
              if (_collection.isWhitelist)
                Tab(text: '白名单 (${_whitelistUsers.length})')
              else
                const Tab(text: '信息'),
            ],
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: [
            _buildVideosTab(),
            _collection.isWhitelist ? _buildWhitelistTab() : _buildInfoTab(),
          ],
        ),
        floatingActionButton: widget.isSharedView
            ? null  // 共享视图模式下不显示编辑按钮
            : (_tabController.index == 0
                ? FloatingActionButton(
                    onPressed: _addVideo,
                    child: const Icon(Icons.add),
                  )
                : (_collection.isWhitelist
                    ? FloatingActionButton(
                        onPressed: _addWhitelistUser,
                        child: const Icon(Icons.person_add),
                      )
                    : null)),
      ),
    );
  }

  /// 构建视频列表标签页
  Widget _buildVideosTab() {
    if (_isLoadingVideos) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_videos.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.video_library_outlined,
              size: 80,
              color: Colors.grey[300],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无视频',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '点击右下角按钮添加视频',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadVideos,
      child: ReorderableListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _videos.length,
        onReorder: _onReorderVideos,
        itemBuilder: (context, index) {
          final video = _videos[index];
          return _buildVideoCard(video, index);
        },
      ),
    );
  }

  /// 构建视频卡片
  Widget _buildVideoCard(CollectionVideoModel video, int index) {
    return Card(
      key: ValueKey(video.id),
      margin: const EdgeInsets.only(bottom: 12),
      child: InkWell(
        onTap: () => _playVideo(video),
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              // 排序手柄
              Icon(Icons.drag_handle, color: Colors.grey[400]),
              const SizedBox(width: 8),
              
              // 序号
              Container(
                width: 28,
                height: 28,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Text(
                  '${index + 1}',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Theme.of(context).primaryColor,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              
              // 视频图标和时长
              Container(
                width: 80,
                height: 60,
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Stack(
                  children: [
                    // 视频图标
                    Center(
                      child: Icon(
                        Icons.play_circle_outline,
                        size: 32,
                        color: Colors.grey[500],
                      ),
                    ),
                    // 时长标签
                    Positioned(
                      right: 4,
                      bottom: 4,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 4,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.black.withValues(alpha: 0.7),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          video.formattedDuration,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 10,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 12),
              
              // 视频信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      video.title,
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        Icon(Icons.play_arrow, size: 14, color: Colors.grey[500]),
                        const SizedBox(width: 4),
                        Text(
                          '${video.playCount}次播放',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              
              // 操作按钮
              IconButton(
                icon: const Icon(Icons.delete_outline, color: Colors.red),
                onPressed: () => _deleteVideo(video),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 视频排序
  void _onReorderVideos(int oldIndex, int newIndex) {
    setState(() {
      if (newIndex > oldIndex) {
        newIndex -= 1;
      }
      final video = _videos.removeAt(oldIndex);
      _videos.insert(newIndex, video);
    });

    // 保存新排序
    final videoIds = _videos.map((v) => v.id).toList();
    _collectionService.updateVideoOrder(_collection.id, videoIds).then((_) {
      _hasChanges = true;
      Logger.d('COLLECTION_DETAIL', '视频排序已更新');
    }).catchError((e) {
      Logger.e('COLLECTION_DETAIL', '更新排序失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('更新排序失败: $e')),
      );
      _loadVideos(); // 重新加载恢复原排序
    });
  }

  /// 构建白名单标签页
  Widget _buildWhitelistTab() {
    if (_isLoadingWhitelist) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_whitelistUsers.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.people_outline,
              size: 80,
              color: Colors.grey[300],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无白名单用户',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '点击右下角按钮添加用户',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadWhitelist,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _whitelistUsers.length,
        itemBuilder: (context, index) {
          final user = _whitelistUsers[index];
          return _buildWhitelistUserCard(user);
        },
      ),
    );
  }

  /// 构建白名单用户卡片
  Widget _buildWhitelistUserCard(WhitelistUserModel user) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: CircleAvatar(
          backgroundImage: user.userAvatar != null && user.userAvatar!.isNotEmpty
              ? NetworkImage(user.userAvatar!)
              : null,
          child: user.userAvatar == null || user.userAvatar!.isEmpty
              ? const Icon(Icons.person)
              : null,
        ),
        title: Text(user.username ?? '未知用户'),
        subtitle: Text(
          '添加于 ${_formatDate(user.createTime)}',
          style: TextStyle(fontSize: 12, color: Colors.grey[600]),
        ),
        trailing: IconButton(
          icon: const Icon(Icons.remove_circle_outline, color: Colors.red),
          onPressed: () => _removeWhitelistUser(user),
        ),
      ),
    );
  }

  /// 构建信息标签页
  Widget _buildInfoTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 封面
          if (_collection.coverUrl != null && _collection.coverUrl!.isNotEmpty)
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedImageWidget(
                imageUrl: _collection.coverUrl,
                width: double.infinity,
                height: 200,
                fit: BoxFit.cover,
                imageType: '集合封面',
              ),
            ),
          const SizedBox(height: 16),
          
          // 基本信息
          _buildInfoItem('标题', _collection.title),
          if (_collection.description != null)
            _buildInfoItem('描述', _collection.description!),
          _buildInfoItem('状态', _collection.statusText),
          _buildInfoItem('访问权限', _collection.accessTypeText),
          _buildInfoItem('视频数量', '${_collection.videoCount}个'),
          _buildInfoItem('总时长', _collection.formattedDuration),
          _buildInfoItem('浏览次数', '${_collection.viewsCount}次'),
          _buildInfoItem('点赞数', '${_collection.likesCount}'),
          _buildInfoItem('创建时间', _formatDate(_collection.createTime)),
          _buildInfoItem('更新时间', _formatDate(_collection.updateTime)),
          
          // 标签
          if (_collection.tags.isNotEmpty) ...[
            const SizedBox(height: 16),
            const Text(
              '标签',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _collection.tags.map((tag) {
                return Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    tag,
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 12,
                    ),
                  ),
                );
              }).toList(),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建信息项
  Widget _buildInfoItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }

  /// 添加视频
  void _addVideo() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _AddVideoSheet(
        collectionId: _collection.id,
        collectionService: _collectionService,
        onVideoAdded: () {
          _hasChanges = true;
          _loadVideos();
          _refreshCollection();
        },
      ),
    );
  }
}

/// 添加视频的底部弹窗
class _AddVideoSheet extends StatefulWidget {
  final int collectionId;
  final CollectionService collectionService;
  final VoidCallback onVideoAdded;

  const _AddVideoSheet({
    required this.collectionId,
    required this.collectionService,
    required this.onVideoAdded,
  });

  @override
  State<_AddVideoSheet> createState() => _AddVideoSheetState();
}

class _AddVideoSheetState extends State<_AddVideoSheet> {
  /// 图片选择器
  final ImagePicker _imagePicker = ImagePicker();
  
  /// 视频文件
  File? _videoFile;
  
  /// 标题控制器
  final _titleController = TextEditingController();
  
  /// 描述控制器
  final _descriptionController = TextEditingController();
  
  /// 是否正在上传
  bool _isUploading = false;
  
  /// 上传进度提示
  String _uploadStatus = '';
  
  /// 压缩进度
  double _compressProgress = 0;
  
  /// 视频时长（秒）
  int _videoDuration = 0;
  
  /// 订阅压缩进度
  Subscription? _compressSubscription;

  @override
  void initState() {
    super.initState();
    // 监听压缩进度
    _compressSubscription = VideoCompress.compressProgress$.subscribe((progress) {
      setState(() {
        _compressProgress = progress;
      });
    });
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    _compressSubscription?.unsubscribe();
    super.dispose();
  }

  /// 选择视频
  Future<void> _selectVideo() async {
    showModalBottomSheet(
      context: context,
      builder: (ctx) => Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '选择视频',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                  child: _buildOptionButton(
                    icon: Icons.video_library,
                    label: '从相册选择',
                    onTap: () {
                      Navigator.pop(ctx);
                      _pickVideoFromGallery();
                    },
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: _buildOptionButton(
                    icon: Icons.videocam,
                    label: '录制视频',
                    onTap: () {
                      Navigator.pop(ctx);
                      _recordVideo();
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  /// 构建选项按钮
  Widget _buildOptionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey[300]!),
        ),
        child: Column(
          children: [
            Icon(icon, size: 32, color: Colors.blue[600]),
            const SizedBox(height: 8),
            Text(label, style: const TextStyle(fontSize: 14)),
          ],
        ),
      ),
    );
  }

  /// 从相册选择视频
  Future<void> _pickVideoFromGallery() async {
    try {
      final XFile? video = await _imagePicker.pickVideo(
        source: ImageSource.gallery,
        maxDuration: const Duration(minutes: 30),
      );
      if (video != null) {
        await _processSelectedVideo(File(video.path));
      }
    } catch (e) {
      Logger.e('ADD_VIDEO', '选择视频失败: $e');
      _showError('选择视频失败: $e');
    }
  }

  /// 录制视频
  Future<void> _recordVideo() async {
    try {
      final XFile? video = await _imagePicker.pickVideo(
        source: ImageSource.camera,
        maxDuration: const Duration(minutes: 10),
      );
      if (video != null) {
        await _processSelectedVideo(File(video.path));
      }
    } catch (e) {
      Logger.e('ADD_VIDEO', '录制视频失败: $e');
      _showError('录制视频失败: $e');
    }
  }

  /// 处理选中的视频
  Future<void> _processSelectedVideo(File videoFile) async {
    setState(() {
      _videoFile = videoFile;
    });
    
    // 尝试获取视频信息
    try {
      final info = await VideoCompress.getMediaInfo(videoFile.path);
      if (info.duration != null) {
        setState(() {
          _videoDuration = (info.duration! / 1000).round();
        });
      }
    } catch (e) {
      Logger.w('ADD_VIDEO', '获取视频信息失败: $e');
    }
    
    Logger.d('ADD_VIDEO', '选择视频成功: ${videoFile.path}');
  }

  /// 上传视频到集合
  Future<void> _uploadVideo() async {
    // 验证
    if (_videoFile == null) {
      _showError('请先选择视频');
      return;
    }
    if (_titleController.text.trim().isEmpty) {
      _showError('请输入视频标题');
      return;
    }

    setState(() {
      _isUploading = true;
      _uploadStatus = '准备上传...';
      _compressProgress = 0;
    });

    try {
      // 1. 压缩视频
      setState(() => _uploadStatus = '正在压缩视频...');
      final compressedVideo = await CompressUtils.compressVideo(_videoFile!);
      final videoToUpload = compressedVideo ?? _videoFile!;
      
      // 获取压缩后视频的信息
      int durationSec = _videoDuration;
      if (compressedVideo != null) {
        try {
          final info = await VideoCompress.getMediaInfo(compressedVideo.path);
          if (info.duration != null) {
            durationSec = (info.duration! / 1000).round();
          }
        } catch (e) {
          Logger.w('ADD_VIDEO', '获取压缩后视频信息失败: $e');
        }
      }
      
      // 2. 上传视频（使用集合专用上传接口，文件会存储到集合目录下）
      setState(() => _uploadStatus = '正在上传视频...');
      final videoUrl = await widget.collectionService.uploadVideo(
        videoToUpload,
        collectionId: widget.collectionId,
      );
      Logger.d('ADD_VIDEO', '视频上传成功: $videoUrl');
      
      // 3. 添加到集合（不需要封面，集合本身有封面）
      setState(() => _uploadStatus = '正在保存...');
      await widget.collectionService.addVideo(
        collectionId: widget.collectionId,
        videoUrl: videoUrl,
        title: _titleController.text.trim(),
        description: _descriptionController.text.trim().isEmpty 
            ? null 
            : _descriptionController.text.trim(),
        durationSec: durationSec,
        // 不传coverUrl，集合内视频不需要单独封面
      );
      
      Logger.d('ADD_VIDEO', '视频添加到集合成功');
      
      // 关闭弹窗并刷新
      Navigator.pop(context);
      widget.onVideoAdded();
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('视频添加成功！'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      Logger.e('ADD_VIDEO', '上传失败: $e');
      _showError('上传失败: $e');
    } finally {
      setState(() {
        _isUploading = false;
        _uploadStatus = '';
      });
    }
  }

  /// 显示错误
  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  /// 格式化时长
  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final secs = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.85,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        children: [
          // 顶部拖动条
          Container(
            margin: const EdgeInsets.only(top: 12),
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          
          // 标题栏
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: _isUploading ? null : () => Navigator.pop(context),
                  child: const Text('取消'),
                ),
                const Text(
                  '添加视频',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                TextButton(
                  onPressed: _isUploading ? null : _uploadVideo,
                  child: _isUploading
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : const Text('上传'),
                ),
              ],
            ),
          ),
          
          const Divider(height: 1),
          
          // 上传进度提示
          if (_isUploading)
            Container(
              padding: const EdgeInsets.all(16),
              color: Colors.blue[50],
              child: Column(
                children: [
                  Row(
                    children: [
                      const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Text(
                          _uploadStatus,
                          style: TextStyle(color: Colors.blue[700]),
                        ),
                      ),
                    ],
                  ),
                  if (_uploadStatus.contains('压缩视频') && _compressProgress > 0)
                    Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: LinearProgressIndicator(
                        value: _compressProgress / 100,
                        backgroundColor: Colors.blue[100],
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.blue[600]!),
                      ),
                    ),
                ],
              ),
            ),
          
          // 内容区域
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(16),
              children: [
                // 视频选择区域
                _buildSectionTitle('视频文件', required: true),
                const SizedBox(height: 8),
                GestureDetector(
                  onTap: _isUploading ? null : _selectVideo,
                  child: Container(
                    height: 180,
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.grey[300]!),
                    ),
                    child: _videoFile != null
                        ? Stack(
                            children: [
                              // 视频预览（使用封面或占位）
                              Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.video_file,
                                      size: 48,
                                      color: Colors.green[600],
                                    ),
                                    const SizedBox(height: 8),
                                    Text(
                                      '视频已选择',
                                      style: TextStyle(
                                        color: Colors.green[600],
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    if (_videoDuration > 0)
                                      Text(
                                        '时长: ${_formatDuration(_videoDuration)}',
                                        style: TextStyle(
                                          color: Colors.grey[600],
                                          fontSize: 12,
                                        ),
                                      ),
                                  ],
                                ),
                              ),
                              // 更换按钮
                              Positioned(
                                right: 8,
                                top: 8,
                                child: Container(
                                  padding: const EdgeInsets.all(4),
                                  decoration: BoxDecoration(
                                    color: Colors.black54,
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: const Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Icon(Icons.edit, color: Colors.white, size: 14),
                                      SizedBox(width: 4),
                                      Text(
                                        '更换',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 12,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          )
                        : Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.video_library,
                                size: 48,
                                color: Colors.grey[400],
                              ),
                              const SizedBox(height: 12),
                              Text(
                                '点击选择视频',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 14,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '支持MP4格式，最长30分钟',
                                style: TextStyle(
                                  color: Colors.grey[400],
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ),
                  ),
                ),
                const SizedBox(height: 20),
                
                // 视频标题
                _buildSectionTitle('视频标题', required: true),
                const SizedBox(height: 8),
                TextField(
                  controller: _titleController,
                  enabled: !_isUploading,
                  decoration: InputDecoration(
                    hintText: '请输入视频标题',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 14,
                    ),
                  ),
                  maxLength: 50,
                ),
                const SizedBox(height: 12),
                
                // 视频描述
                _buildSectionTitle('视频描述'),
                const SizedBox(height: 8),
                TextField(
                  controller: _descriptionController,
                  enabled: !_isUploading,
                  decoration: InputDecoration(
                    hintText: '请输入视频描述（可选）',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 14,
                    ),
                  ),
                  maxLines: 3,
                  maxLength: 200,
                ),
                
                const SizedBox(height: 20),
                
                // 提示信息
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.blue[200]!),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.info_outline, color: Colors.blue[700], size: 20),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          '视频上传前会自动压缩，以减少上传时间和流量消耗',
                          style: TextStyle(
                            color: Colors.blue[700],
                            fontSize: 13,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                
                const SizedBox(height: 40),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建区域标题
  Widget _buildSectionTitle(String title, {bool required = false}) {
    return Row(
      children: [
        Text(
          title,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
        if (required)
          const Text(
            ' *',
            style: TextStyle(
              color: Colors.red,
              fontSize: 16,
            ),
          ),
      ],
    );
  }
}
